package com.doubi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubi.constants.SystemConstants;
import com.doubi.mapper.AdverMapper;
import com.doubi.model.sys.TAdver;
import com.doubi.model.sys.TArea;
import com.doubi.modelvo.sys.AdverVo;
import com.doubi.utils.DataUtil;
import com.doubi.utils.JsonUtils;
import com.doubi.vo.AppModel;
import com.doubi.vo.AppUiModel;
import com.doubi.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AdverService extends ServiceImpl<AdverMapper, TAdver> {
    @Autowired
    private AdverMapper adverMapper;


    public AppUiModel<List<AdverVo>> getList(Integer position){
        QueryWrapper<TAdver> wrapper = new QueryWrapper<>();
        wrapper.eq("position",position);
        wrapper.orderByAsc("sort_num");
        return new AppUiModel<>(JsonUtils.copyList(adverMapper.selectList(wrapper),AdverVo.class));
    }
    public PageVo<TAdver> getPage(PageVo<TAdver> pageVo,TAdver adver){
        QueryWrapper<TAdver> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        adverMapper.selectPage(pageVo,wrapper);
        return pageVo;
    }

    public AppModel delBean(String oid){
        TAdver adver = adverMapper.selectById(oid);
        if(DataUtil.isNotEmpty(adver)){
            adverMapper.deleteById(adver.getOid());
            return AppModel.success();
        }else {
            return AppModel.error();
        }
    }

    public AppModel saveOrUpdateBean(TAdver adver){
        if(DataUtil.isEmpty(adver.getOid())){
            adver.setCreateTime(new Date());
            adver.setIsDelete(1);
            adver.setStatus(1);
            adverMapper.insert(adver);
            return AppModel.success();
        }else {
            TAdver bean = adverMapper.selectById(adver.getOid());
            bean.setImgUrl(adver.getImgUrl());
            bean.setSortNum(adver.getSortNum());
            bean.setPosition(adver.getPosition());
            bean.setLinkUrl(adver.getLinkUrl());
            bean.setUpdateTime(new Date());
            adverMapper.updateById(bean);
            return AppModel.success();
        }
    }

    /**
     * 功能说明：广告 更新状态
     * @param oid bean
     * @return AppModel
     */
    public AppModel updateStatus(String oid) {
        TAdver adver = adverMapper.selectById(oid);
        if (DataUtil.isEmpty(adver)) {
            return new AppModel(-1, "参数错误！");
        } else {
            if(adver.getStatus().equals(SystemConstants.STATUS.STATUS_1)){
                adver.setStatus(SystemConstants.STATUS.STATUS_0);
            }else {
                adver.setStatus(SystemConstants.STATUS.STATUS_1);
            }
            adverMapper.updateById(adver);
            return new AppModel(0, "修改成功！");
        }
    }
}
